/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.mk.transaction.requesttowarehouse;

import com.ronsicecream.pos.out.transaction.requesttowarehouse.*;
import com.buanalintas.bynga.Access;
import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.ronsicecream.pos.entities.PosMasterPriceWarehouse;
import com.ronsicecream.pos.entities.PosMasterStatus;
import com.ronsicecream.pos.entities.PosMasterUnit;
import com.ronsicecream.pos.entities.PosTransactionOutRequestMaterialToWarehouse;
import com.ronsicecream.pos.entities.PosTransactionOutRequestMaterialToWhDetail;
import com.ronsicecream.pos.master.status.Status;
import com.ronsicecream.pos.mk.transaction.requesttowarehousedetail.RequestDetail;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author user
 */
public class Request extends Page {

    private Field requestId;
    private Field requestNumber;
    private Field requestDate;
    private Field requestQuantity;
//    private Field requestNeededDate;
    private Field requestProgress;
    private Field requestRejectReason;
    private Field requestDescription;
    private Field requestTimestamp;
    private Field requestPosUnitId;
    private Field requestUserId;
    private Field requestUnitId;
    private Field requestRegionalId;
    private Field requestDestinationUnitId;
    private Action actionRevision = new Action("revisi", "Revision Request");
    private Action actionReject = new Action("reject", "Reject Request");
    private Action actionAgree = new Action("approve", "Agree Request");

    public Request() {
        super();

        setTheClass(PosTransactionOutRequestMaterialToWarehouse.class);

        setPageDetail(RequestDetail.class);


        requestId = new Field();
        requestId.setName("requestId");
        requestId.setCaption("id");
        //requestId.setInfo("request id");
        requestId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        requestId.setInputProperties(" size=\"20\"");
        getFields().add(requestId);

        requestNumber = new Field();
        requestNumber.setName("requestNumber");
        requestNumber.setCaption("number");
        requestNumber.setRequired(true);
        requestNumber.setListProperties(" align=\"left\" width=\"15%\" nowrap");
        requestNumber.setInputProperties(" size=\"30\" readonly");
        getFields().add(requestNumber);

        requestQuantity = new Field();
        requestQuantity.setName("requestQuantity");
        requestQuantity.setCaption("qantity");
        //requestNumber.setInfo("request number");
        requestQuantity.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        requestQuantity.setInputProperties(" size=\"20\"");
        getFields().add(requestQuantity);

        requestDate = new Field();
        requestDate.setName("requestDate");
        requestDate.setCaption("date");
        requestDate.setRequired(true);
        requestDate.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        requestDate.setInputProperties(" size=\"8\"");
        requestDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(requestDate);

//        requestNeededDate = new Field();
//        requestNeededDate.setName("requestNeededDate");
//        requestNeededDate.setCaption("needed date");
////        requestNeededDate.setRequired(true);
//        requestNeededDate.setListProperties(" align=\"center\" width=\"5%\" nowrap");
//        requestNeededDate.setInputProperties(" size=\"8\"");
////        requestNeededDate.setFormatter(DateFormatter.getInstanceDate(this));
//        getFields().add(requestNeededDate);


        requestProgress = new Field();
        requestProgress.setName("requestProgress");
        requestProgress.setCaption("progress");
        //requestProgress.setInfo("purchase order progress");
        requestProgress.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        requestProgress.getOptions().add(new String[]{"1", "NEW"});
        requestProgress.getOptions().add(new String[]{"2", "REJECT"});
        requestProgress.getOptions().add(new String[]{"3", "REVISION"});
        requestProgress.getOptions().add(new String[]{"4", "APPROVED"});
        getFields().add(requestProgress);

        requestRejectReason = new Field();
        requestRejectReason.setName("requestRejectReason");
        requestRejectReason.setCaption("reject reason");
        //requestRejectReason.setInfo("request reject reason");
        requestRejectReason.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        requestRejectReason.setInputProperties(" size=\"20\"");
        getFields().add(requestRejectReason);

        requestDescription = new Field();
        requestDescription.setName("requestDescription");
        requestDescription.setCaption("description");
        //requestDescription.setInfo("request description");
        requestDescription.setListProperties(" align=\"left\" width=\"30%\" nowrap");
        requestDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        requestDescription.setInputType(Field.INPUT_TEXT_AREA);
        requestDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(requestDescription);

        requestTimestamp = new Field();
        requestTimestamp.setName("requestTimestamp");
        requestTimestamp.setCaption("timestamp");
        //requestTimestamp.setInfo("request timestamp");
        requestTimestamp.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        requestTimestamp.setInputProperties(" size=\"12\"");
//        requestTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));
        getFields().add(requestTimestamp);

        requestUnitId = new Field();
        requestUnitId.setName("requestUnitId");
        requestUnitId.setCaption("unit");
        //posTransactionRequestFromOutletDetailCollection.setInfo("pos transaction request from outlet detail collection");
        requestUnitId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        requestUnitId.setInputProperties(" size=\"20\"");
        getFields().add(requestUnitId);

        requestRegionalId = new Field();
        requestRegionalId.setName("requestRegionalId");
        requestRegionalId.setCaption("regional");
        requestRegionalId.setRequired(true);
        requestRegionalId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        requestRegionalId.setInputProperties(" size=\"20\"");
        getFields().add(requestRegionalId);

        requestPosUnitId = new Field();
        requestPosUnitId.setName("requestPosUnitId");
        requestPosUnitId.setCaption("unit");
        requestPosUnitId.setRequired(true);
        requestPosUnitId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        requestPosUnitId.setInputProperties(" size=\"20\"");
        getFields().add(requestPosUnitId);

        requestUserId = new Field();
        requestUserId.setName("requestUserId");
        requestUserId.setCaption("user");
        //posMasterRegional.setInfo("pos master regional");
        requestUserId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        requestUserId.setInputProperties(" size=\"20\"");
        getFields().add(requestUserId);

        requestDestinationUnitId = new Field();
        requestDestinationUnitId.setName("requestDestinationUnitId");
        requestDestinationUnitId.setCaption("to Unit");
        requestDestinationUnitId.setRequired(true);
        requestDestinationUnitId.setSelectorCondition(" t.unitUnitTypeId.unitTypeId=6");
        requestDestinationUnitId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        requestDestinationUnitId.setInputProperties(" size=\"20\"");
        getFields().add(requestDestinationUnitId);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);
        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(requestNumber);
//        getFieldsAdd().add(requestRegionalId);
        getFieldsAdd().add(requestDestinationUnitId);
        getFieldsAdd().add(requestDate);
//        getFieldsAdd().add(requestNeededDate);
        getFieldsAdd().add(requestDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(requestNumber);
//        getFieldsEdit().add(requestRegionalId);
        getFieldsEdit().add(requestDestinationUnitId);
        getFieldsEdit().add(requestDate);
        getFieldsEdit().add(requestRejectReason);
        getFieldsEdit().add(requestDescription);

        getFieldsList().clear();
        getFieldsList().add(requestNumber);
        getFieldsList().add(requestDate);
//        getFieldsList().add(requestPosUnitId);
        getFieldsList().add(requestDestinationUnitId);
        getFieldsList().add(requestRejectReason);
        getFieldsList().add(requestProgress);
        getFieldsList().add(requestQuantity);
//        getFieldsList().add(requestRegionalId);
        getFieldsList().add(requestDescription);

        getFieldsView().clear();
        getFieldsView().add(requestNumber);
        getFieldsView().add(requestRejectReason);
        getFieldsView().add(requestProgress);
//        getFieldsView().add(requestRegionalId);
//        getFieldsView().add(requestPosUnitId);
        getFieldsView().add(requestQuantity);
        getFieldsView().add(requestDescription);
        getFieldsView().add(requestUserId);
        getFieldsView().add(requestUnitId);
        getFieldsView().add(requestTimestamp);

        setController(new RequestWarehouseController(this));

        getActions().add(actionRevision);
        getActions().add(actionAgree);
        getActions().add(actionReject);

        setExportList(getClass().getResourceAsStream("RequestList.jasper"));
        setExport(getClass().getResourceAsStream("Request.jasper"));

    }

    class RequestWarehouseController extends Controller {

        public RequestWarehouseController(Page page) {
            super(page);
            setOrder(requestTimestamp);
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data, List list) {

            System.out.println(1 + "<<=========dedy=");
            PosTransactionOutRequestMaterialToWarehouse request = (PosTransactionOutRequestMaterialToWarehouse) data;
            request.setRequestNumber(generate());
            request.setRequestProgress("1");
            request.setRequestUnitId(getCurrentUnit());
            request.setRequestUserId(getCurrentUser());
            request.setRequestTimestamp(Utility.getTimestamp());


        }

        @Override
        public void beforeUpdate(Object data, List list, List listDelete) {
            PosTransactionOutRequestMaterialToWarehouse request = (PosTransactionOutRequestMaterialToWarehouse) data;
            request.setRequestProgress("1");
            request.setRequestRejectReason(Dictionary.getValue(page, "Revision") + ": " + request.getRequestRejectReason());
        }

//        @Override
//        public void afterUpdate(Object data, List list, List listDelete) {
//            EntityManager em = getEntityManager();
//            PosMasterStatus statusGood = Status.getStatusGood(em);
//            try {
//                em.getTransaction().begin();
//                PosTransactionOutRequestMaterialToWarehouse request = (PosTransactionOutRequestMaterialToWarehouse) data;
////                PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
////                        + " WHERE t.unitUnitTypeId.unitTypeId=4 "
////                        + " AND t.unitUnitId.unitId=" + getCurrentUnit().getUnitId()
////                        + " AND t.unitRegionalId.regionalId=" + request.getRequestRegionalId().getRegionalId())
////                        .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
////                System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName());
////                request.setRequestPosUnitId(posunit);
//                int j = 0;
//                BigDecimal total = BigDecimal.ZERO;
//                BigDecimal totalQty = BigDecimal.ZERO;
//                for (Object details : list) {
//                    PosTransactionOutRequestMaterialToWhDetail requestdetail = (PosTransactionOutRequestMaterialToWhDetail) details;
////                    PosTransactionDistributionDetail requestDistributionDetail = new PosTransactionDistributionDetail();
//                    System.out.println("ceking========>" + j++);
//                    PosMasterPriceWarehouse price = (PosMasterPriceWarehouse) em.createQuery("SELECT t FROM PosMasterPriceWarehouse t"
//                        + " WHERE t.pricePosUnitId.unitId="+request.getRequestDestinationUnitId().getUnitId()
//                        + " AND t.priceItemId.itemId=" + requestdetail.getRequestDetailItemId().getItemId()
////                        + " AND t.unitRegionalId.regionalId=" + request.getRequestRegionalId().getRegionalId()
//                        )
//                        .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
//                        
//                        requestdetail.setRequestDetailPrice(price.getPricePrice());
////                    requestdetail.setRequestDexDetailPrepare(0);
//                    totalQty = totalQty.add(requestdetail.getRequestDetailQuantity());
//                    total = total.add(requestdetail.getRequestDetailPrice().multiply(requestdetail.getRequestDetailQuantity()));
//
////                    requestdetail.setRequestDexDetailStatusId(statusGood);
//                }
//                System.out.println("totalQty========>" + totalQty);
//                request.setRequestQuantity(totalQty);
//                System.out.println("total========>" + total);
//                request.setRequestTotal(total);
////                request.setRequestDexProgress("1");
//
//
//                em.getTransaction().commit();
//            } catch (Exception e) {
//                Logger.getInstance().log(e);
//            }
//        }
        @Override
        public void afterInsert(Object data, List list) {
            EntityManager em = getEntityManager();
            PosMasterStatus statusGood = Status.getStatusGood(em);
            try {
                em.getTransaction().begin();
                PosTransactionOutRequestMaterialToWarehouse request = (PosTransactionOutRequestMaterialToWarehouse) data;
                int j = 0;
                BigDecimal total = BigDecimal.ZERO;
                BigDecimal totalQty = BigDecimal.ZERO;
                PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
                        + " WHERE t.unitUnitTypeId.unitTypeId=3 "
                        + " AND t.unitUnitId.unitId=" + getCurrentUnit().getUnitId() //                        + " AND t.unitRegionalId.regionalId=" + request.getRequestRegionalId().getRegionalId()
                        )
                        .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName());
                request.setRequestPosUnitId(posunit);
                request.setRequestRegionalId(posunit.getUnitRegionalId());
                for (Object details : list) {
                    PosTransactionOutRequestMaterialToWhDetail requestdetail = (PosTransactionOutRequestMaterialToWhDetail) details;
//                    PosTransactionDistributionDetail requestDistributionDetail = new PosTransactionDistributionDetail();
                    System.out.println("ceking========>" + j++);
                    PosMasterPriceWarehouse price = (PosMasterPriceWarehouse) em.createQuery("SELECT t FROM PosMasterPriceWarehouse t"
                            + " WHERE t.pricePosUnitId.unitId=" + request.getRequestDestinationUnitId().getUnitId()
                            + " AND t.priceItemId.itemId=" + requestdetail.getRequestDetailItemId().getItemId() //                        + " AND t.unitRegionalId.regionalId=" + request.getRequestRegionalId().getRegionalId()
                            )
                            .setHint(Persistence.REFRESH_HINT, true).getSingleResult();

                    requestdetail.setRequestDetailPrice(price.getPricePrice());
//                    requestdetail.setRequestDexDetailPrepare(0);
                    totalQty = totalQty.add(requestdetail.getRequestDetailQuantity());
                    total = total.add(requestdetail.getRequestDetailPrice().multiply(requestdetail.getRequestDetailQuantity()));

//                    requestdetail.setRequestDexDetailStatusId(statusGood);
                }
                System.out.println("totalQty========>" + totalQty);
                request.setRequestQuantity(totalQty);
//                System.out.println("total========>" + total);
                request.setRequestTotal(total);
//                request.setRequestDexProgress("1");



                em.getTransaction().commit();
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
        }
    }

    @Override
    public String addJavascript() {
        return "<script>function __revision(id) {var reason = prompt('" + Dictionary.getValue(this, "Enter revision reason") + "?', ''); if (reason != null) { location.href = \"?m=" + getMenu().getMenuName() + "&a=" + actionRevision.getName() + "&id=\"+id+\"&reason=\"+escape(reason); } return false; };function __reject(id) {var reason = prompt('" + Dictionary.getValue(this, "Enter rejected reason") + "?', ''); if (reason != null) { location.href = \"?m=" + getMenu().getMenuName() + "&a=" + actionReject.getName() + "&id=\"+id+\"&reason=\"+escape(reason); } return false; }</script>";
    }

    @Override
    public boolean isGranted(Action action, Object data) {
        boolean granted = super.isGranted(action, data);
        if (granted) {
            PosTransactionOutRequestMaterialToWarehouse request = (PosTransactionOutRequestMaterialToWarehouse) data;
            if (action.equals(Action.EDIT) || action.equals(Action.TRANS_EDIT) || action.equals(Action.DELETE)) {
                granted = request.getRequestProgress() == null || request.getRequestProgress().equals("1") || request.getRequestProgress().equals("2");
            }
        }
        return granted;
    }

    @Override
    public String delete(Object data) {
        String delete = super.delete(data);
        if (delete == null) {
            PosTransactionOutRequestMaterialToWarehouse request = (PosTransactionOutRequestMaterialToWarehouse) data;
            if (!"1".equals(request.getRequestProgress())) {
                delete = Dictionary.getValue(this, "can not be deleted");
            }
        }
        return delete;
    }

    @Override
    public StringBuffer processCustomRowCommand(StringBuffer template, Page page, Object data) {
        StringBuffer commands = new StringBuffer();
        StringBuffer command = null;
        PosTransactionOutRequestMaterialToWarehouse request = (PosTransactionOutRequestMaterialToWarehouse) data;
        if (request.getRequestProgress() == null || request.getRequestProgress().equals("1")) {
            if (Access.isGranted(page, actionRevision)) {
                command = new StringBuffer(template.toString());
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionRevision.getName() + "&id=" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Revision request"));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __revision('" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())) + "')\"");
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=command-revision.png");
                commands.append(command.toString());
            }
            if (Access.isGranted(page, actionReject)) {
                command = new StringBuffer(template.toString());
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionReject.getName() + "&id=" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Reject request"));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __reject('" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())) + "')\"");
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=command-reject.png");
                commands.append(command.toString());
            }
            if (Access.isGranted(page, actionAgree)) {
                command = new StringBuffer(template.toString());
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionAgree.getName() + "&id=" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Approve request"));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return confirm('" + Dictionary.getValue(page, "Approve request") + "?')\"");
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=command-approve.png");
                commands.append(command.toString());
            }
        }
        return commands;
    }

    @Override
    public String doAction() {

        String id = Utility.decode(Utility.getParameter(getRequest(), "id"));
        if (id != null && !id.trim().equals("")) {
            PosTransactionOutRequestMaterialToWarehouse data = (PosTransactionOutRequestMaterialToWarehouse) getController().getData(id);
            if (getAction().equals(actionRevision)) {
                String reason = Utility.getParameter(getRequest(), "reason");
                if (reason == null || reason.trim().equals("")) {
                    return "err:" + Dictionary.getValue(this, "Please enter revision reason");
                }
                try {
                    data.setRequestProgress("2");
                    data.setRequestRejectReason(Utility.getParameter(getRequest(), "reason"));
                    getController().update(data);
                    return "ok:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected succesfully");
                } catch (Exception e) {
                    Logger.getInstance().log(e);
                    return "err:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected failed") + ": " + e.getMessage();
                }
            } else if (getAction().equals(actionReject)) {
                String reason = Utility.getParameter(getRequest(), "reason");
                if (reason == null || reason.trim().equals("")) {
                    return "err:" + Dictionary.getValue(this, "Please enter rejected reason");
                }
                try {
                    data.setRequestProgress("3");
                    data.setRequestRejectReason(Utility.getParameter(getRequest(), "reason"));
                    getController().update(data);
                    return "ok:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected succesfully");
                } catch (Exception e) {
                    Logger.getInstance().log(e);
                    return "err:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected failed") + ": " + e.getMessage();
                }
            } else if (getAction().equals(actionAgree)) {
                EntityManager em = getEntityManager();
                PosMasterStatus statusGood = Status.getStatusGood(em);
                try {
                    em.getTransaction().begin();
                    PosTransactionOutRequestMaterialToWarehouse request = (PosTransactionOutRequestMaterialToWarehouse) data;
                    int j = 0;
                    BigDecimal total = BigDecimal.ZERO;
                    BigDecimal totalQty = BigDecimal.ZERO;
                    System.out.println(id + "  id");

//                    PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
//                            + " WHERE t.unitUnitTypeId.unitTypeId=4 "
//                            + " AND t.unitUnitId.unitId=" + getCurrentUnit().getUnitId()
////                            + " AND t.unitRegionalId.regionalId=" + request.getRequestRegionalId().getRegionalId()
//                            )
//                            .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
//                    System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName());
//                    request.setRequestPosUnitId(posunit);
//

                    List<PosTransactionOutRequestMaterialToWhDetail> details = em.createQuery("SELECT t FROM PosTransactionOutRequestMaterialToWhDetail t "
                            + "WHERE t.requestDetailRequestId.requestId='" + id.toString() + "'").setHint(Persistence.REFRESH_HINT, true).getResultList();


                    for (PosTransactionOutRequestMaterialToWhDetail detail : details) {

                        PosMasterPriceWarehouse price = (PosMasterPriceWarehouse) em.createQuery("SELECT t FROM PosMasterPriceWarehouse t"
                                + " WHERE t.pricePosUnitId.unitId=" + request.getRequestDestinationUnitId().getUnitId()
                                + " AND t.priceItemId.itemId=" + detail.getRequestDetailItemId().getItemId() //                        + " AND t.unitRegionalId.regionalId=" + request.getRequestRegionalId().getRegionalId()
                                )
                                .setHint(Persistence.REFRESH_HINT, true).getSingleResult();

                        detail.setRequestDetailPrice(price.getPricePrice());

                        total = total.add(detail.getRequestDetailPrice().multiply(detail.getRequestDetailQuantity()));
                        totalQty = totalQty.add(detail.getRequestDetailQuantity());

                    }

                    System.out.println("totalQty :" + totalQty);

                    request.setRequestTotal(total);
                    request.setRequestProgress("4");
                    request.setRequestQuantity(totalQty);

//                    distribution.setDistributionTotal(total);
//                    distribution.setDistributionQuantity(totalQty);
//                    distribution.setDistributionSent(BigDecimal.ZERO);
//                    distribution.setDistributionUnsent(totalQty);
//                    em.persist(distribution);


                    em.getTransaction().commit();
                } catch (Exception e) {
                    System.out.println("error :" + e);
                    return "err:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "approved failed") + ": " + e.getMessage();
                }
            }
        }
        return null;
    }

    @Override
    public void beforeAdd() {
        requestNumber.setDefaultValue(generate());
    }

    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionOutRequestMaterialToWarehouse request = (PosTransactionOutRequestMaterialToWarehouse) getEntityManager().createQuery("SELECT t FROM PosTransactionOutRequestMaterialToWarehouse t WHERE t.requestNumber LIKE '%/" + unitCode + "/Rons/REQ-Outlet/%/" + year + "' ORDER BY t.requestTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(request.getRequestNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/Rons/REQ-Outlet/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/Rons/REQ-Outlet/" + month + "/" + year;
    }
}
